﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace zanpen2000.common
{
    /// <summary>
    /// 位移文件首字节实现加密，不能加密 小于 512 字节的文件
    /// </summary>
    public class ByteCrypto
    {

        private const int byte_count = 512;

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="filename"></param>
        public static void FileEncrypt(string filename)
        {
            //不重复加密
            if (IsEncrypt(filename)) return;

            byte[] buffer = new byte[byte_count];

            var file = System.IO.File.OpenRead(filename);
            
            file.Read(buffer, 0, buffer.Length);
            file.Close();

            using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.OpenOrCreate))
            {
                fs.Seek(0, System.IO.SeekOrigin.Begin);
                for (int i = 0; i < byte_count; i++)
                {
                    fs.WriteByte(0);
                }

                fs.Seek(fs.Length, System.IO.SeekOrigin.Begin);
                fs.Write(buffer, 0, buffer.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="filename"></param>
        public static void FileDecrypt(string filename)
        {
            //不重复解密
            if (!IsEncrypt(filename)) return;

            byte[] buffer = new byte[byte_count];

            var file = System.IO.File.OpenRead(filename);
            file.Seek(file.Length - byte_count, System.IO.SeekOrigin.Begin);
            file.Read(buffer, 0, buffer.Length);
            file.Close();

            using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.OpenOrCreate))
            {
                fs.Seek(0, System.IO.SeekOrigin.Begin);
                for (int i = 0; i < byte_count; i++)
                {
                    fs.WriteByte(buffer[i]);
                }
                fs.Flush();
            }
        }

        /// <summary>
        /// 检测是否加密
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool IsEncrypt(string filename)
        {
            byte[] buffer = new byte[byte_count];
            var file = System.IO.File.OpenRead(filename);
            file.Read(buffer, 0, buffer.Length);
            file.Close();

            return buffer.All(b => b.Equals(0));
        }

        public static void AutoCrypt(string filename)
        {
            if (IsEncrypt(filename)) FileDecrypt(filename);
            else FileEncrypt(filename);
        }
    }
}
